<template>
  <div>
    <a-card title="人员选择" class="general-card">
      <a-scrollbar style="height: 60vh; overflow: auto">
        <a-skeleton v-if="treeData.length === 0" animation>
          <!-- 还在加载的时候用骨架屏先占个位子，好看点 -->
          <a-skeleton-line :rows="10" />
        </a-skeleton>
        <div v-else>
          <!-- <a-input-search
            v-model="searchTreeKey"
            style="margin-bottom: 5px"
            @input="searchTreeData"
          /> -->
          <a-tree
            v-model:selected-keys="selectedTreeKeys"
            v-model:expanded-keys="expandedTreeKeys"
            block-node
            :field-names="{
              key: 'code',
              title: 'name',
              children: 'children',
            }"
            :data="treeDataFilter"
            @select="onSelectTreeNode"
          >
            <template #icon>
              <icon-home />
            </template>
          </a-tree>
        </div>
      </a-scrollbar>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { h, ref, watch } from 'vue';
  import { queryDeptRecordTreeList } from '@/api/system/dept';
  import { queryUserRecordList } from '@/api/system/user';
  import iconUser from '@arco-design/web-vue/es/icon/icon-user';

  const treeData = ref<any[]>([]); // 树
  const treeDataLoading = ref<boolean>(false);
  const treeDataFilter = ref<any[]>([]);
  const parentKeys = ref<string[]>([]);
  const dataList = ref<any[]>([]); // treeData的所有key:title:id
  const filterKeySet = new Set(); // 定义一个集合，用于记录过滤keys
  const expandedTreeKeys = ref<string[]>([]); // 已展开的树节点keys
  const selectedTreeKeys = ref<string[]>([]); // 已选中的树节点keys
  // const searchTreeKey = ref<string>(); // 树顶上的搜索框关键字
  watch(
    () => parentKeys,
    (val) => {
      if (val) {
        val.value.forEach((element: any) => {
          filterKeySet.add(element);
        });
        // 进行过滤操作
        treeDataFilter.value = treeData.value.filter((item) =>
          filterKeySet.has(item.code)
        );
        expandedTreeKeys.value = [...filterKeySet] as string[];
        console.log(filterKeySet, treeDataFilter, expandedTreeKeys, '-=-');
      }
    },
    { deep: true, immediate: true }
  );
  const emit = defineEmits(['personalClick']);
  /**
   * func
   */
  /**
   * @description 获取部门的树形结构信息
   */
  const getTreeData = async () => {
    treeDataLoading.value = true;
    treeData.value = [];
    treeDataFilter.value = [];
    try {
      const { data } = await queryDeptRecordTreeList({});
      treeData.value = data;
      treeDataFilter.value = data;
      dataList.value = [];
      generateList(treeData.value);
    } catch (error) {
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
    } finally {
      treeDataLoading.value = false;
    }
  };
  /**
   * @description 构建treeData的所有 { key: title: id } 数组
   * @param data 树节点数据
   */
  const generateList = (data: any) => {
    // 创建dataList 递归调用
    data.forEach((item: any) => {
      const node = item;
      const key = node.code;
      dataList.value.push({ key, title: node.name, id: node.id });
      if (node.children) {
        generateList(node.children);
      } else {
        node.children = [];
      }
    });
  };
  /**
   * @description 获取完整地父节点的key数组 递归调用
   * @param key
   */
  // const getWholeParentKeys = (key: string) => {
  //   const temp = getParentKey(key, treeData.value);
  //   if (temp !== undefined) {
  //     parentKeys.value.push(temp);
  //     getWholeParentKeys(temp);
  //   }
  // };
  /**
   * @description 树形结构上面的搜索框发生改变会触发此函数
   * @param value
   */
  // const searchTreeData = (val: any) => {
  //   const value = val.replaceAll(' ', '');
  //   filterKeySet.clear();
  //   // 进行搜索操作
  //   const expandedKeysTemp = [] as any[];
  //   dataList.value.forEach((item) => {
  //     if (item.title && item.title.indexOf(value) > -1) {
  //       expandedKeysTemp.push(item.key);
  //     }
  //   });
  //   parentKeys.value = [];
  //   // 必须要有下面这个forEach，否则只能查到2层数据，因为超过了2层后匹配不到更上层的父id，进而导致搜索不出结果
  //   expandedKeysTemp.forEach((item: string) => {
  //     filterKeySet.add(item);
  //     getWholeParentKeys(item); // 把原始的expandedKeysTemp中的每个key对应的完整父key都放进parentKeys保存
  //   });
  //   expandedTreeKeys.value =
  //     value.trim().length === 0 ? [] : ([...filterKeySet] as string[]);
  //   searchTreeKey.value = value;
  //   // 进行过滤操作
  //   treeDataFilter.value = treeData.value.filter((item) =>
  //     filterKeySet.has(item.code)
  //   );
  // };
  /**
   * @description 根据子节点的key获取父节点的key
   * @param key key
   * @param tree 树节点
   */
  // const getParentKey = (key: string, tree: any) => {
  //   let parentKey;
  //   tree.forEach((elem: any) => {
  //     const node = elem;
  //     if (node.children) {
  //       if (node.children.some((item: any) => item.code === key)) {
  //         parentKey = node.code;
  //       } else if (getParentKey(key, node.children)) {
  //         parentKey = getParentKey(key, node.children);
  //       }
  //     }
  //   });
  //   return parentKey;
  // };
  /**
   * @method
   * @description 获取人员数据
   */
  const getTbDataByPage = async (obj) => {
    const params = {
      page: 1,
      limit: 10000,
      ...obj,
    };
    try {
      const { data } = await queryUserRecordList(params);
      data.list.forEach((item: any) => {
        item.activated = item.activated ? 'true' : 'false'; // 这个true和false要用单引号包一层，否则select组件不认识boolean类型的初始值
        item.secretLevel = String(item.secretLevel); // 用户密级也要用单引号包一层，否则数据字典组件不认识number类型的值
      });
      return data.list;
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
      return undefined;
    }
  };
  const onSelectTreeNode = async (newSelectedKeys: any, event: any) => {
    if (event.node.username) {
      emit('personalClick', event.node);
      return;
    }
    selectedTreeKeys.value = newSelectedKeys;
    if (event.node.children) {
      let flag = false;
      expandedTreeKeys.value.forEach((item: string) => {
        if (item === newSelectedKeys[0]) {
          flag = true;
        }
      });
      if (!flag) {
        expandedTreeKeys.value.push(newSelectedKeys[0]);
      }
    }
    console.log(newSelectedKeys, event);
    const arr = await getTbDataByPage({ deptCode: newSelectedKeys[0] }); // 按条件查询，注意：这里不能用searchRef.value.handleSubmit();方法，会滞后一步，可能是setFormValues内部还没遍历结束就handleSubmit了一下
    const treeNewData = arr.map((element) => {
      element.name = element.username;
      element.code = element.userCode;
      element.icon = () => h(iconUser);
      return element;
    });
    event.node.children = setNew([...event.node.children, ...treeNewData]);
  };
  const setNew = (arr) => {
    const result = [];
    const obj = {};
    for (let i = 0; i < arr.length; i += 1) {
      if (!obj[arr[i].id]) {
        result.push(arr[i]);
        obj[arr[i].id] = true;
      }
    }
    return result;
  };
  getTreeData();
</script>
